package cn.appsys.tools;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileSave {
	public String upLoad(MultipartFile attach, HttpServletRequest request) {
		String PicPath = null;
		String path=null;
		String fileName=null;
		if (!attach.isEmpty()) {
			// 获取路径
			 path = request.getSession().getServletContext()
					.getRealPath("statics" + File.separator + "uploadFile");
			// 设置文件名
			 fileName= System.currentTimeMillis()
					+ RandomUtils.nextInt(1000000) + "_Personal.jpg";
			// 控制大小
			if (attach.getSize() > 50000) {
				request.setAttribute("uploadFileError", "文件大小不能超过50KB");
				return "文件大小错误！";
			}

			File targetFile = new File(path, fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			try {
				attach.transferTo(targetFile);
				PicPath = request.getContextPath() + File.separator + "statics"
						+ File.separator + "uploadFile" + File.separator
						+ fileName;
			} catch (Exception e) {
				e.printStackTrace();
				return "上传错误";
			}
		}
		return PicPath+"+"+path+File.separator+fileName;
	}
	
	public String upLoadFile(MultipartFile attach, HttpServletRequest request,
			int size,String name) {
		String PicPath = null;
		String path=null;
		String fileName=null;
		if (!attach.isEmpty()) {
			// 获取路径
			 path = request.getSession().getServletContext()
					.getRealPath("statics" + File.separator + "uploadFile");
			// 设置文件名
			fileName = System.currentTimeMillis()
					+ RandomUtils.nextInt(1000000) + name;
			// 控制大小
			if (attach.getSize() > size) {
				return "文件大小错误！";
			}

			File targetFile = new File(path, fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			try {
				attach.transferTo(targetFile);
				PicPath = request.getContextPath() + File.separator + "statics"
						+ File.separator + "uploadFile" + File.separator
						+ fileName;
			} catch (Exception e) {
				e.printStackTrace();
				return "上传错误";
			}
		}
		return PicPath+"+"+path+File.separator+fileName;
	}
}
